package wang.encoding.mroot.plugin.ueditor.hunter;

import java.io.File;
import java.util.*;

import org.apache.commons.io.FileUtils;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import wang.encoding.mroot.plugin.ueditor.PathFormat;
import wang.encoding.mroot.plugin.ueditor.define.AppInfo;
import wang.encoding.mroot.plugin.ueditor.define.BaseState;
import wang.encoding.mroot.plugin.ueditor.define.MultiState;
import wang.encoding.mroot.plugin.ueditor.define.State;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.storage.model.FileListing;
import com.qiniu.util.Auth;

import javax.servlet.http.HttpServletRequest;


/**
 * 文件管理
 *
 * @author ErYang
 */
public class FileManager {

    private String[] allowFiles;
    private int count;
    public static String accessKey;
    public static String secretKey;
    public static String baseUrl;
    public static String bucket;
    public static String uploadDirPrefix;
    public static Zone zone;

    public static Boolean uploadLocal;

    /**
     * 配置
     *
     * @param conf Map<String, Object>
     */
    public FileManager(final Map<String, Object> conf) {
        //String rootPath = (String) conf.get("rootPath");
        //String dir = rootPath + conf.get("dir");
        this.allowFiles = this.getAllowFiles(conf.get("allowFiles"));
        this.count = (Integer) conf.get("count");

    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 文件列表
     *
     * @param index  int
     * @param marker String
     * @return State
     */
    public State listFile(final int index, final String marker) {
        FileListing fileListing;
        State state;
        List<String> fileList = new ArrayList<>();
        try {
            if (uploadLocal) {
                String filePath = Objects.requireNonNull(ClassUtils.getDefaultClassLoader().getResource("")).getPath();
                File dir = new File(filePath + "static/assets/upload/");
                if (!dir.exists()) {
                    return new BaseState(false, AppInfo.NOT_EXIST);
                }
                if (!dir.isDirectory()) {
                    return new BaseState(false, AppInfo.NOT_DIRECTORY);
                }
                Collection<File> list = FileUtils.listFiles(dir, this.allowFiles, true);
                if (index < 0 || index > list.size()) {
                    state = new MultiState(true);
                } else {
                    Object[] fileList2 = Arrays.copyOfRange(list.toArray(), index, index + this.count);
                    state = this.getState(fileList2);
                }
                state.putInfo("start", (long) index);
                state.putInfo("total", (long) list.size());
            } else {
                Auth auth = Auth.create(accessKey, secretKey);
                Configuration configuration = new Configuration(zone);
                BucketManager bucketManager = new BucketManager(auth, configuration);
                fileListing = bucketManager.listFiles(bucket, null, marker != null && !"".equals(marker) ? marker : null, count, null);
                for (FileInfo fileInfo : fileListing.items) {
                    fileList.add(fileInfo.key);
                }
                state = this.getState(fileList.toArray(new String[0]));
                state.putInfo("start", (long) index);
                state.putInfo("isLast", fileListing.isEOF() + "");
                state.putInfo("marker", fileListing.marker);
                state.putInfo("total", (long) Integer.MAX_VALUE);
            }
        } catch (QiniuException e) {
            e.printStackTrace();
            state = new BaseState(false, AppInfo.NOT_EXIST);
        }
        return state;
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 得到状态
     *
     * @param files Object[]
     * @return State
     */
    private State getState(final Object[] files) {
        MultiState state = new MultiState(true);
        BaseState fileState;
        File file;
        for (Object url : files) {
            if (url == null) {
                break;
            }
            file = (File) url;
            fileState = new BaseState(true);
            if (uploadLocal) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                        .getRequest();
                String requestUrl = request.getScheme() + "://" + request.getServerName() + ":"
                        + request.getServerPort() + request.getContextPath();
                fileState.putInfo("url", requestUrl + PathFormat.format(this.getPath(file)));
            } else {
                fileState.putInfo("url", baseUrl + "/" + url);
            }
            state.addState(fileState);
        }
        return state;
    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 得到路径
     *
     * @param file File
     * @return String
     */
    private String getPath(final File file) {
        String path = PathFormat.format(file.getAbsolutePath());
        //String str = ClassUtils.getDefaultClassLoader().getResource("/").getPath();
        String str = path.substring(0, path.indexOf("assets"));
        return path.replace(str, "/");

    }

    // -------------------------------------------------------------------------------------------------

    /**
     * 得到文件
     *
     * @param fileExt Object
     * @return String[]
     */
    private String[] getAllowFiles(final Object fileExt) {
        String[] eats;
        String ext;
        if (fileExt == null) {
            return new String[0];
        }
        eats = (String[]) fileExt;
        for (int i = 0, len = eats.length; i < len; i++) {
            ext = eats[i];
            eats[i] = ext.replace(".", "");
        }
        return eats;
    }

    // -------------------------------------------------------------------------------------------------

}

// -----------------------------------------------------------------------------------------------------

// End FileManager class

/* End of file FileManager.kt */
/* Location: ./src/main/kotlin/wang/encoding/mroot/plugin/ueditor/hunter/FileManager.kt */

// -----------------------------------------------------------------------------------------------------
// +----------------------------------------------------------------------------------------------------
// |                           ErYang出品 属于小极品  O(∩_∩)O~~   共同学习    共同进步
// +----------------------------------------------------------------------------------------------------
// -----------------------------------------------------------------------------------------------------
